import React, { Component } from 'react'
import styles from './index.module.scss'
import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Input,
  Modal,
  Radio,
  Select,
  Space,
  Upload,
  message
} from 'antd'
import { Link } from 'react-router-dom'
import { PlusOutlined } from '@ant-design/icons'
import Channel from 'components/Channel'
import { baseURL } from 'utils/request'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { getArticleById, updateArticle, publishArticle } from 'api/article'

export default class ArticlePublish extends Component {
  state = {
    type: 1,
    fileList: [],
    previewOpen: false,
    previewUrl: '',
    id: this.props.match.params.id
  }

  formRef = React.createRef()
  render() {
    console.log('文章id：', this.state.id)

    return (
      <div className={styles.root}>
        <Card
          title={
            <Breadcrumb
              items={[
                {
                  title: <Link to="/home">首页</Link>
                },
                {
                  title: this.state.id ? '修改文章' : '发布文章'
                }
              ]}
            />
          }
        >
          <Form
            labelCol={{
              span: 4
              // offset: 8
            }}
            wrapperCol={{
              span: 6
            }}
            onFinish={this.onFinish}
            initialValues={{
              content: '',
              type: this.state.type
            }}
            ref={this.formRef}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[
                {
                  required: true,
                  message: '文章标题不能为空'
                }
              ]}
            >
              <Input placeholder="请输入标题" />
            </Form.Item>

            <Form.Item
              name="channel_id"
              label="频道"
              rules={[
                {
                  required: true,
                  message: '频道不能为空'
                }
              ]}
            >
              <Channel></Channel>
            </Form.Item>
            {/* 封面类型 */}
            <Form.Item label="封面" name="type">
              <Radio.Group onChange={this.changeType}>
                <Radio value={1}> 单图 </Radio>
                <Radio value={3}> 三图 </Radio>
                <Radio value={0}> 无图 </Radio>
              </Radio.Group>
            </Form.Item>

            {this.state.type !== 0 && (
              // 上传封面
              <Form.Item
                label="Upload"
                valuePropName="fileList"
                rules={[
                  {
                    required: true
                  }
                ]}
              >
                <Upload
                  listType="picture-card"
                  action={`${baseURL}upload`}
                  fileList={this.state.fileList}
                  // 接口参数名称，默认为file
                  name="image"
                  onChange={this.handleChange}
                  onPreview={this.handlePreview}
                  beforeUpload={this.beforeUpload}
                >
                  {this.state.fileList.length < this.state.type && (
                    <div>
                      <PlusOutlined />
                      <div
                        style={{
                          marginTop: 8
                        }}
                      >
                        Upload
                      </div>
                    </div>
                  )}
                </Upload>
                <Modal
                  open={this.state.previewOpen}
                  title="预览"
                  footer={null}
                  onCancel={this.handleCancel}
                >
                  <img
                    alt="example"
                    style={{ width: '100%' }}
                    src={this.state.previewUrl}
                  />
                </Modal>
              </Form.Item>
            )}
            <Form.Item
              label="内容"
              name="content"
              wrapperCol={{
                span: 12
              }}
              rules={[{ required: true, message: '文章内容不能为空' }]}
            >
              <ReactQuill
                theme="snow"
                placeholder="请输入文章内容"
              ></ReactQuill>
            </Form.Item>

            <Form.Item
              wrapperCol={{
                offset: 4,
                span: 16
              }}
            >
              <Space>
                <Button type="primary" htmlType="submit" size="large">
                  {this.state.id ? '编辑文章' : '发布文章'}
                </Button>
                <Button size="large" onClick={this.addDraft}>
                  存入草稿
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
  // DOM渲染完成后
  componentDidMount() {
    if (this.state.id) {
      // 如果是修改页面，请求详情数据
      this.getInfo(this.state.id)
    }
  }
  // 页面加载完毕
  // async componentDidMount() {
  //   console.log('页面加载完毕', this.state.id)
  //   console.log(this.props)
  //   if (this.state.id) {
  //     // 需要发送请求，获取文章详细信息
  //     const res = await getArticleById(this.state.id)
  //     // 处理请求结果，用来回显
  //     const values = {
  //       ...res.data
  //     }
  //     // 给表单设置 values 值
  //     this.formRef.current.setFieldsValue(values)
  // // state中数据单独处理
  // const fileList = res.data.cover.images.map((item) => {
  //   return { url: item }
  // })
  // this.setState({
  //   fileList,
  //   type: res.data.cover.type
  // })
  //   }
  // }

  // 切换封面的个数
  changeType = (e) => {
    // console.log(e)
    this.setState({
      type: e.target.value,
      // 清空fileList
      fileList: []
    })
  }
  // 上传中、完成、失败都会调用这个函数
  handleChange = ({ file, fileList }) => {
    // if (file.error) {
    //   message.error(file.response.message)
    //   fileList.pop()
    // }
    // console.log(file)
    // console.log(file.response)
    // 上传后，把回调的 fileList 修改到 state中
    this.setState({
      fileList
    })
  }
  handlePreview = (file) => {
    console.log(file)

    const url = file.url || file.response.data.url
    this.setState({
      previewOpen: true,
      previewUrl: url
    })
  }
  handleCancel = () => {
    this.setState({
      previewOpen: false
    })
  }
  beforeUpload = (file) => {
    // console.log(file)
    if (file.size >= 1024 * 500) {
      message.warning('上传的文件不能超过500kb')
      return Upload.LIST_IGNORE
    }
    if (!['image/png', 'image/jpeg'].includes(file.type)) {
      message.warning('只能上传jpg或者jpeg类型的图片')
      return Upload.LIST_IGNORE
    }
    return true
  }
  // 发布文章&保存草稿的公用代码部分
  save = async (values, draft = false) => {
    if (this.state.fileList.length !== this.state.type) {
      return message.warning('上传的图片数量不正确')
    }
    const images = this.state.fileList.map((item) => {
      console.log(item)
      if (item.url) return item.url
      else return item.response.data.url
    })
    const data = {
      ...values,
      cover: {
        type: values.type,
        images
      }
    }
    delete data.type
    if (!this.state.id) {
      // 新增文章
      await publishArticle(
        {
          ...values,
          cover: {
            type: values.type,
            images
          }
        },
        draft
      )
      if (draft) {
        message.success('保存为草稿成功')
      } else {
        message.success('发布文章成功')
      }
    } else {
      // 编辑文章
      await updateArticle(
        {
          ...values,
          cover: {
            type: values.type,
            images
          },
          id: this.state.id
        },
        draft
      )
      if (draft) {
        message.success('发布草稿成功')
      } else {
        message.success('修改文章成功')
      }
    }
    this.props.history.push('/home/list')
  }
  // 发布文章/编辑文章
  onFinish = async (values) => {
    this.save(values)
  }
  addDraft = async () => {
    // 1.校验
    const values = await this.formRef.current.validateFields()
    // console.log(values)
    // 发起请求
    this.save(values, true)
  }
  // 请求文章详情数据，并回显
  getInfo = async (id) => {
    const { data } = await getArticleById(id)
    // 数据回显
    console.log(data)
    this.formRef.current.setFieldsValue(data)
    this.setState({
      type: data.cover.type,
      fileList: data.cover.images.map((item) => ({ url: item }))
    })
  }
}
